﻿using Entity;
using Microsoft.AspNetCore.Http;
using ServiceCore;
using ServiceCore.Tool.Mqtt;
using ServiceCore.Tool.NPOI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace Customer.Bussiness_Service
{
    public interface Irk_data_service
    {
        ResultListModel<search_rk_userlist> get_user_pagelist(search_customer_list query);
        ResultListModel<search_rk_mchlist> get_mch_pagelist(Base_List_Params query);
        /// <summary>
        ///  重置修改用户权限
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultModel reset_user_info(reset_user_info_params query);
        /// <summary>
        /// 设置机器图片信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultModel set_mch_pic(set_mch_pic_parmas query);
        /// <summary>
        /// 设置机器开始质保时间以及机器类型
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        ResultModel set_mch_base(set_mch_parmas model);
        /// <summary>
        ///  管理员查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<search_rk_adminmchlist> get_adminmch_pagelist(admin_mch_params query);

        ResultObjModel set_brightness(string mchid, decimal value);
        ResultObjModel sub_brightness(string mchid, decimal value);
        ResultObjModel run_cmd(string action, string mchid);
        ResultModel confirm_cmd(string cmd_id, string remark);
        ResultListModel<SearchMch_CMD_Log> Get_MchCmdLog_List(CMDLog_List_Params query);
        /// <summary>
        /// 统计查询机器
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<customer_repair_showpic_ForexcelPage> get_customer_pic_for_excel(search_customer_pic_for_excel query);
        void down_customer_pic_for_excel(search_customer_pic_for_excel query);
        /// <summary>
        /// 获取锁列表信息 
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<SearchRK_Lock_Log> get_lock_list(lock_List_Params query);
    }
    public class rk_data_service : Irk_data_service
    {
        private readonly IToole_DI _tool;
        private readonly IRK_Mqtt _rkMqtt;
        private readonly INpoi_service _excelservice;
        private readonly IHttpContextAccessor _context;
        public rk_data_service(IToole_DI Tool, IRK_Mqtt RkMqtt, INpoi_service Excelservice, IHttpContextAccessor Context)
        {
            _tool = Tool;
            _rkMqtt = RkMqtt;
            _excelservice = Excelservice;
            _context = Context;
        }
        public ResultListModel<search_rk_userlist> get_user_pagelist(search_customer_list query)
        {
            return CoreStartDo.ResultAction<ResultListModel<search_rk_userlist>>(result =>
            {
                if (string.IsNullOrWhiteSpace(query.sn) && string.IsNullOrWhiteSpace(query.search_value) && string.IsNullOrWhiteSpace(query.customer_uname) && !query.search_type.HasValue && string.IsNullOrWhiteSpace(query.SerchKeyword))
                {
                    return new ResultListModel<search_rk_userlist>()
                    {
                        code = 0,
                        current = 1,
                        msg = "success",
                        rows = null,
                        total = 0
                    };
                }
                string baseuserid = "";
                if (!string.IsNullOrWhiteSpace(query.sn))
                {
                    baseuserid = _tool.di_db.Get_rk_List<string>("select baseuserid from Mch where sn=@sn", new { sn = query.sn }).FirstOrDefault();
                    if (baseuserid == "")
                    {
                        baseuserid = "and 1=2";
                    }
                }
                string sql = "select *,(select count(*) from mch where mch.BaseUserId = [user].Id) as MchCount from [user]";
                string where = " where 1=1 and parentId is null";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (!string.IsNullOrWhiteSpace(baseuserid))
                {
                    where += $" and Id = @baseuserid";
                    query_dy.baseuserid = baseuserid;
                }
                ///如果没有设置SN并且设置了搜索条件才应该进入该判断
                if (string.IsNullOrWhiteSpace(query.sn) && query.search_type.HasValue)
                {
                    switch (query.search_type.Value)
                    {
                        case search_enum_type.客户电话:
                            if (!string.IsNullOrWhiteSpace(query.search_value))
                            {
                                where += $" and Tel like @Tel";
                                query_dy.Tel = $"%{query.search_value}%";
                            }
                            else {
                                where += " and 1=2";
                            }
                            break;
                        case search_enum_type.客户微信号:
                            if (!string.IsNullOrWhiteSpace(query.search_value))
                            {
                                where += $" and wx_name like @wx_name";
                                query_dy.wx_name = $"%{query.search_value}%";
                            }
                            else
                            {
                                where += " and 1=2";
                            }
                            break;
                        case search_enum_type.客户姓名:
                            if (!string.IsNullOrWhiteSpace(query.search_value))
                            {
                                where += $" and Name like @Name";
                                query_dy.Name = $"%{query.search_value}%";
                            }
                            else
                            {
                                where += " and 1=2";
                            }
                            break;
                        case search_enum_type.客户账号:
                            if (!string.IsNullOrWhiteSpace(query.search_value))
                            {
                                where += $" and UserName like @UserName";
                                query_dy.UserName = $"%{query.search_value}%";
                            }
                            else
                            {
                                where += " and 1=2";
                            }
                            break;
                    }
                }
                result = _tool.di_db.GetRKPageList<search_rk_userlist>(sql, where, "CreateOn", query_dy, query.IsPage, query.page, query.pagesize);
                return result;
            });
        }

        public ResultListModel<search_rk_mchlist> get_mch_pagelist(Base_List_Params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<search_rk_mchlist>>(result =>
            {
                string sql = "select b.iccid,a.* from mch a left join SimBoss_BindMch b on a.Id = b.MchID";
                string where = " where 1=1 ";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (string.IsNullOrWhiteSpace(query.SerchKeyword))
                {
                    return new ResultListModel<search_rk_mchlist>();
                }
                else
                {
                    //if (query.Issale)
                    //{
                    //    where += " and a.work_baseuserid=@baseuserid";
                    //    query_dy.baseuserid = query.SerchKeyword;
                    //}
                    //else {
                        where += " and a.baseuserid=@baseuserid";
                        query_dy.baseuserid = query.SerchKeyword;
                    //}
                }
                result = _tool.di_db.GetRKPageList<search_rk_mchlist>(sql, where, "a.CreateOn", query_dy, query.IsPage, query.page, query.pagesize);
                foreach (var item in result.rows)
                {
                    item.have_pic = !string.IsNullOrWhiteSpace(item.tallyafter_screenshot) && !string.IsNullOrWhiteSpace(item.wxrecord_screenshot);
                    if (!string.IsNullOrWhiteSpace(item.Key) && item.Key.Length > 6)
                    {
                        try
                        {
                            item.mch_info_list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Mchinfo>>(item.Key);
                        }
                        catch {

                        }
                    }
                }
                return result;
            });
        }


        //private string[] reset_user_info_audit = new string[] {
        //    "Customer","all_Customer"
        //};
        public ResultModel reset_user_info(reset_user_info_params model)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(model.Id))
                {
                    result.code = 1;
                    result.msg = "用户id未入参";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.Tel))
                {
                    result.code = 1;
                    result.msg = "用户联系电话必须填写";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.wx_name))
                {
                    result.code = 1;
                    result.msg = "用户微信名必须填写";
                    return result;
                }
                //if (string.IsNullOrWhiteSpace(model.name))
                //{
                //    result.code = 1;
                //    result.msg = "请输入用户姓名";
                //    return result;
                //}
                //判断当前登录人权限
                //if (!reset_user_info_audit.Contains(_tool.di_user.USER.role_id))
                //{
                //    result.code = 1;
                //    result.msg = "您的权限无法执行该操作";
                //    return result;
                //}
                //判断电话号码是否存在其他ID的项
                var Checkuser = _tool.di_db.Get_rk_List<string>("select name from [user] where Tel=@Tel and Id<>@Id", model);
                if (Checkuser.Any())
                {
                    result.code = 0;
                    result.msg = $"联系电话已存在_{Checkuser.FirstOrDefault()}";
                }
                //开始执行任务
                int update_row = _tool.di_db.do_rk_Execute("update [user] set Tel=@tel,wx_name=@wx_name,Name=@name where Id=@Id", model);
                if (update_row > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "保存失败";
                }
                return result;
            });

        
        }

        /// <summary>
        /// 设置机器图片
        /// </summary>
        /// <returns></returns>
        public ResultModel set_mch_pic(set_mch_pic_parmas model)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(model.Id))
                {
                    result.code = 1;
                    result.msg = "机器ID未入参";
                    return result;
                }
                if (model.wxrecord_screenshot == null || !model.wxrecord_screenshot.Any())
                {
                    result.code = 1;
                    result.msg = "微信截图记录未上传";
                    return result;
                }
                if (model.tallyafter_screenshot == null || !model.tallyafter_screenshot.Any())
                {
                    result.code = 1;
                    result.msg = "留货后售货机照片未上传";
                    return result;
                }
                //检测机器是否存在
                var checkUser = _tool.di_db.Get_rk_List<Mch>("select * from Mch where id=@Id", new { Id = model.Id }).FirstOrDefault();
                if (checkUser == null)
                {
                    result.code = 1;
                    result.msg = "指定设置机器不存在";
                    return result;
                }
                string needupdatetime = ",screenshot_subtime=@screenshot_subtime";
                if (checkUser.screenshot_subtime.HasValue)
                {
                    needupdatetime = "";
                }
                int update_row = _tool.di_db.do_rk_Execute($"update Mch set wxrecord_screenshot=@wxrecord_screenshot,tallyafter_screenshot=@tallyafter_screenshot,screenshot_subname=@screenshot_subname,screenshot_subuid=@screenshot_subuid{needupdatetime} where id=@Id", new
                {
                    model.Id,
                    wxrecord_screenshot = Newtonsoft.Json.JsonConvert.SerializeObject(model.wxrecord_screenshot),
                    tallyafter_screenshot = Newtonsoft.Json.JsonConvert.SerializeObject(model.tallyafter_screenshot),
                    screenshot_subtime = DateTime.Now,
                    screenshot_subname = _tool.di_user.USER.u_name,
                    screenshot_subuid = _tool.di_user.USER.uid
                });
                if (update_row > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 0;
                    result.msg = "保存失败";
                }
                return result;
            });
        }
        /// <summary>
        ///  设置机器类型和时间
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultModel set_mch_base(set_mch_parmas model) {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(model.Id))
                {
                    result.code = 1;
                    result.msg = "机器ID未入参";
                    return result;
                }
                if (!model.assurance_sdt.HasValue)
                {
                    result.code = 1;
                    result.msg = "请输入质保开始时间";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.MchType))
                {
                    result.code = 1;
                    result.msg = "请输入机器类型";
                    return result;
                }
                //检测机器是否存在
                var checkUser = _tool.di_db.Get_rk_List<Mch>("select * from Mch where id=@Id", new { Id = model.Id }).FirstOrDefault();
                if (checkUser == null)
                {
                    result.code = 1;
                    result.msg = "指定设置机器不存在";
                    return result;
                }
                int update_row = _tool.di_db.do_rk_Execute("update Mch set assurance_sdt=@assurance_sdt,MchType=@MchType,service_tel=@service_tel where id=@Id", model);
                if (update_row > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 0;
                    result.msg = "保存失败";
                }
                return result;
            });
        }
        /// <summary>
        /// 返回快捷查询机器列
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<search_rk_adminmchlist> get_adminmch_pagelist(admin_mch_params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<search_rk_adminmchlist>>(result =>
            {
                string sql = "select b.iccid,a.*,c.Name as baseusername,c.UserName from mch a left join SimBoss_BindMch b on a.Id = b.MchID left join [user] c on a.baseuserid = c.Id";
                string where = " where 1=1 ";
                dynamic query_dy = new System.Dynamic.ExpandoObject(); 
                if (!string.IsNullOrWhiteSpace(query.baseuserid))
                {
                    where += " and a.baseuserid=@baseuserid";
                    query_dy.baseuserid = query.baseuserid;
                }
                if (!string.IsNullOrWhiteSpace(query.sn))
                {
                    where += " and a.sn like @sn";
                    query_dy.sn = $"%{query.sn}%";
                }
                if (!string.IsNullOrWhiteSpace(query.mchid))
                {
                    where += " and a.Id like @mchid";
                    query_dy.mchid = $"%{query.mchid}%";
                }
                if (!string.IsNullOrWhiteSpace(query.mchname))
                {
                    where += " and a.Name like @mchname";
                    query_dy.mchname = $"%{query.mchname}%";
                }
                result = _tool.di_db.GetRKPageList<search_rk_adminmchlist>(sql, where, "a.CreateOn", query_dy, query.IsPage, query.page, query.pagesize);
                foreach (var item in result.rows)
                {
                    item.have_pic = !string.IsNullOrWhiteSpace(item.tallyafter_screenshot) && !string.IsNullOrWhiteSpace(item.wxrecord_screenshot);
                    if (!string.IsNullOrWhiteSpace(item.Key) && item.Key.Length > 6)
                    {
                        try
                        {
                            item.mch_info_list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Mchinfo>>(item.Key);
                        }
                        catch
                        {

                        }
                    }
                }
                return result;
            });
        }
         
        /// <summary>
        /// 
        /// </summary>
        /// <param name="mchid"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public ResultObjModel set_brightness(string mchid, decimal value)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(mchid))
                {
                    result.code = 1;
                    result.msg = "机器ID必传";
                    return result;
                }
                Mch Mchmodel = _tool.di_db.Get_rk_List<Mch>("select * from mch where Id=@mchid", new { mchid }).FirstOrDefault();
                if (Mchmodel == null)
                {
                    result.code = 1;
                    result.msg = "机器不存在";
                    return result;
                }
                else if (!Mchmodel.Daemon_IsOnline)
                {
                    result.code = 1;
                    result.msg = "机器不在线";
                    return result;
                }
                if (value < 0 || value > 198)
                {
                    result.code = 1;
                    result.msg = "设置数值不合法,必须在0-198之间";
                    return result;
                }
                string cmd_id = Guid.NewGuid().ToString("N");
                string topic = $"rkt/mch/{Mchmodel.SN}AppDaemon/cmd/";
                string data = Newtonsoft.Json.JsonConvert.SerializeObject(new { action = "set_brightness", value, cmd_id });
                //"{\"action\":\"set_brightness\"value}";
                _rkMqtt.Publish(topic, data, MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
                _tool.AddCmdLog(new Mch_CMD_Log()
                {
                    Id = cmd_id,
                    c_type = Cmd_Type.亮度,
                    Mchid = mchid,
                    Sn = Mchmodel.SN,
                    Baseuserid = Mchmodel.BaseUserId
                });
                result.code = 0;
                result.msg = "指令发送成功";
                return result;
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mchid"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public ResultObjModel sub_brightness(string mchid, decimal value)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(mchid))
                {
                    result.code = 1;
                    result.msg = "机器ID必传";
                    return result;
                }
                Mch Mchmodel = _tool.di_db.Get_rk_List<Mch>("select * from mch where Id=@mchid", new { mchid }).FirstOrDefault();
                if (Mchmodel == null)
                {
                    result.code = 1;
                    result.msg = "机器不存在";
                    return result;
                }
                int do_int = _tool.di_db.do_rk_Execute("update Mch set brightness=@brightness where Id=@mchid", new { mchid, brightness = value });
                if (do_int > 0)
                {
                    result.code = 0;
                    result.msg = "Success";
                    result.data = do_int;
                }
                else
                {
                    result.code = 1;
                    result.msg = "保存失败";
                }
                return result;
            });
        }
        private static string[] cmds = new string[] {
            "shutdown","restart","screenshots"
        };
        /// <summary>
        /// 
        /// </summary>
        /// <param name="mchid"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public ResultObjModel run_cmd(string action, string mchid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (!cmds.Contains(action))
                {
                    result.code = 1;
                    result.msg = "未知的指令";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(mchid))
                {
                    result.code = 1;
                    result.msg = "机器ID必传";
                    return result;
                }
                Mch Mchmodel = _tool.di_db.Get_rk_List<Mch>("select * from mch where Id=@mchid", new { mchid }).FirstOrDefault();
                if (Mchmodel == null)
                {
                    result.code = 1;
                    result.msg = "机器不存在";
                    return result;
                }
                else if (!Mchmodel.Daemon_IsOnline)
                {
                    result.code = 1;
                    result.msg = "机器不在线";
                    return result;
                }  
                string cmd_id = Guid.NewGuid().ToString("N");
                string topic = $"rkt/mch/{Mchmodel.SN}AppDaemon/cmd/";
                string mastertopic = $"rkt/mch/{Mchmodel.SN}/cmd/";
                string data = Newtonsoft.Json.JsonConvert.SerializeObject(new { action, cmd_id });
                //"{\"action\":\"set_brightness\"value}";
                _rkMqtt.Publish(topic, data, MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
                _rkMqtt.Publish(mastertopic, data, MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
                Cmd_Type? thistype = null;
                switch (action)
                {
                    case "shutdown":
                        thistype = Cmd_Type.关机;
                        break;
                    case "restart":
                        thistype = Cmd_Type.重启;
                        break;
                    case "screenshots":
                        thistype = Cmd_Type.截屏;
                        break;
                }
                if (thistype != null)
                {
                    _tool.AddCmdLog(new Mch_CMD_Log()
                    {
                        Id = cmd_id,
                        c_type = thistype.Value,
                        Mchid = mchid,
                        Sn = Mchmodel.SN,
                        Baseuserid = Mchmodel.BaseUserId
                    });
                }
                result.code = 0;
                result.msg = "指令发送成功";
                return result;
            });
        }
        /// <summary>
        /// 确认指令接收
        /// </summary>
        /// <param name="mchid"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public ResultModel confirm_cmd(string cmd_id, string remark)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {

                if (string.IsNullOrWhiteSpace(cmd_id))
                {
                    result.code = 1;
                    result.msg = "指令ID必传";
                    return result;
                } 
                Mch_CMD_Log cmdlog = _tool.di_db.Get_rk_List<Mch_CMD_Log>("select * from Mch_CMD_Log where Id=@cmd_id", new { cmd_id }).FirstOrDefault();
                if (cmdlog == null)
                {
                    result.code = 1;
                    result.msg = "指令不存在";
                    return result;
                }
                if (cmdlog.SendState == 1)
                {
                    result.code = 1;
                    result.msg = "指令已确认";
                    return result;
                }
                if (cmdlog.c_type == Cmd_Type.截屏)
                {
                    result.code = 0;
                    result.msg = "success";
                    return result;
                }
                result = _tool.UpdateCmdLog(cmd_id, remark, "");
                return result;
            });
        }


        public ResultListModel<SearchMch_CMD_Log> Get_MchCmdLog_List(CMDLog_List_Params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<SearchMch_CMD_Log>>(result =>
            {

                if (string.IsNullOrWhiteSpace(query.mchid))
                {
                    result.code = 1;
                    result.msg = "机器ID不能为空";
                    return result;
                }
                string sql = "select * from Mch_CMD_Log";
                dynamic serchObj = new System.Dynamic.ExpandoObject();
                string where = $"  where 1=1 and Mchid=@Mchid";
                serchObj.Mchid = query.mchid;
                if (query.SendState.HasValue)
                {
                    where += $"  and SendState=@SendState";
                    serchObj.SendState = query.SendState.Value;
                }
                if (query.c_type.HasValue)
                {
                    where += $"  and c_type=@c_type";
                    serchObj.c_type = query.c_type.Value;
                }
                else
                {
                    where += $"  and c_type<>2";
                }
                if (!string.IsNullOrWhiteSpace(query.starttime))
                {
                    try
                    {
                        DateTime sdt = Convert.ToDateTime(query.starttime);
                        where += $"  and SendTime>=@sdt";
                        serchObj.sdt = sdt;
                    }
                    catch { }
                }
                if (!string.IsNullOrWhiteSpace(query.endtime))
                {
                    try
                    {
                        DateTime edt = Convert.ToDateTime(query.endtime);
                        where += $"  and SendTime<=@edt";
                        serchObj.edt = edt;
                    }
                    catch
                    {

                    }
                }
                //serchObj.adduser = _tool._user.USER.BaseUserId;
                result = _tool.di_db.GetRKPageList<SearchMch_CMD_Log>(sql, where, "SendTime", serchObj, query.IsPage, query.page, query.pagesize);
                result.code = 0;
                result.msg = "success";
                return result;
            });
        }
         
        /// <summary>
        /// 客户确认照片统计
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<customer_repair_showpic_ForexcelPage> get_customer_pic_for_excel(search_customer_pic_for_excel query)
        {
            return CoreStartDo.ResultAction<ResultListModel<customer_repair_showpic_ForexcelPage>>(result =>
            {
                string sql = "select a.*,b.Name as baseusername,b.UserName as baseuserLoginname from Mch a left join [user] b on a.baseuserid=b.Id";
                string where = " where 1=1 and screenshot_subtime is not null";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (!string.IsNullOrWhiteSpace(query.user_name))
                {
                    where += " and (b.Name like @user_name or b.UserName like @user_name)";
                    query_dy.user_name = $"%{query.user_name}%";
                }
                if (!string.IsNullOrWhiteSpace(query.customer_uid))
                {
                    where += " and a.screenshot_subuid=@customer_uid";
                    query_dy.customer_uid = query.customer_uid;
                }
                if (!string.IsNullOrWhiteSpace(query.mch_sn))
                {
                    where += " and a.SN like @mch_sn";
                    query_dy.mch_sn = $"%{query.mch_sn}%";
                }
                if (!string.IsNullOrWhiteSpace(query.mch_name))
                {
                    where += " and a.Id like @mch_name";
                    query_dy.mch_name = $"%{query.mch_name}%";
                }
                //处理时间搜索
                if (!string.IsNullOrWhiteSpace(query.addtime_sdt))
                {
                    where += " and a.screenshot_subtime>=@addtime_sdt";
                    query_dy.addtime_sdt = query.addtime_sdt;
                }
                if (!string.IsNullOrWhiteSpace(query.addtime_edt))
                {
                    where += " and a.screenshot_subtime<=@addtime_edt";
                    query_dy.addtime_edt = query.addtime_edt;
                }
                ResultListModel<MchForSearchPic> result_pagelist = _tool.di_db.GetRKPageList<MchForSearchPic>(sql, where, "a.screenshot_subtime", query_dy, query.IsPage, query.page, query.pagesize);
                var q = from o in result_pagelist.rows
                        select new customer_repair_showpic_ForexcelPage
                        {
                            screenshot_subtime = o.screenshot_subtime.HasValue ? o.screenshot_subtime.Value.ToString("yyyy-MM-dd") : "error",
                            user_name = o.baseusername,
                            mch_type = o.MchType,
                            mch_sn = o.SN,
                            mch_name = o.Name,
                            mch_assurance_sdt = o.assurance_sdt.HasValue ? o.assurance_sdt.Value.ToString("yyyy-MM-dd") : "未设置",
                            customer_uname = o.screenshot_subname,
                            wxrecord_screenshot = o.wxrecord_screenshot, //微信截图
                            tallyafter_screenshot = o.tallyafter_screenshot //理货后微信截图
                        };
                result.code = 0;
                result.msg = "success";
                result.rows = q.ToList();
                result.total = result_pagelist.total;
                result.current = query.page.Value;
                return result;
            });
        }

        public void down_customer_pic_for_excel(search_customer_pic_for_excel query)
        {
            query.IsPage = false;
            var listresult = get_customer_pic_for_excel(query);
            string title = $"{DateTime.Now.ToString("yyyy-MM-dd")}_{_tool.di_user.USER.u_name}_客户确认照片统计.xlsx";
            _excelservice.ExcelExportService(title, listresult.rows, dosomething: fs =>
            {
                _context.HttpContext.Response.ContentType = "application/octet-stream;charset=UTF-8";
                _context.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(title, System.Text.Encoding.UTF8));
                int bufferSize = Convert.ToInt32(fs.Length);
                byte[] buffer;
                buffer = new byte[bufferSize];
                int currentRead = fs.Read(buffer, 0, bufferSize);
                _context.HttpContext.Response.Body.Write(buffer, 0, currentRead);
                _context.HttpContext.Response.Body.Flush();
            });
        }


        /// <summary>
        /// 获取锁列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<SearchRK_Lock_Log> get_lock_list(lock_List_Params query)
        {
            return  CoreStartDo.ResultAction<ResultListModel<SearchRK_Lock_Log>>(result =>
            {
                string sql = " select a.*,b.name as mchname,c.name as bname from RK_Lock_Log a  left join mch b on a.mchid=b.id left join [user] c on a.rk_userid = c.id";
                string where = " where 1=1 ";
                dynamic serchObj = new System.Dynamic.ExpandoObject();
                //sql += $"  and a.baseuserid=@baseuserid";
                //serchObj.baseuserid = _tool._user.USER.BaseUserId;
                if (!string.IsNullOrWhiteSpace(query.mch_id))
                {
                    where += $"  and a.Mchid=@Mchid";
                    serchObj.mch_id = query.mch_id;
                } 
                if (!string.IsNullOrWhiteSpace(query.mch_name))
                {
                    where += $"  and b.name like @mch_name";
                    serchObj.mch_name = $"%{query.mch_name}%";
                }
                if (!string.IsNullOrWhiteSpace(query.mch_sn))
                {
                    where += $"  and b.sn like @mch_sn";
                    serchObj.mch_sn = $"%{query.mch_sn}%";
                }
                if (query.server_opentype.HasValue)
                {
                    where += $"  and a.server_opentype=@server_opentype";
                    serchObj.server_opentype = query.server_opentype;
                }
                if (!string.IsNullOrWhiteSpace(query.SendTime_sdt))
                {
                    where += $"  and a.SendTime>=@SendTime_sdt";
                    serchObj.SendTime_sdt = query.SendTime_sdt;
                }
                if (!string.IsNullOrWhiteSpace(query.SendTime_edt))
                {
                    where += $"  and a.SendTime<=@SendTime_edt";
                    serchObj.SendTime_edt = query.SendTime_edt;
                }
                //serchObj.adduser = _tool._user.USER.BaseUserId;
                result = _tool.di_db.GetRKPageList<SearchRK_Lock_Log>(sql, where, "SendTime", serchObj, query.IsPage, query.page, query.pagesize);
                result.code = 0;
                result.msg = "success";
                return result;
            });
        } 
    }
}
